/*
 * @Author: ZhanXie
 * @Date: 2020-09-02 12:48:19
 * @LastEditors: ZhanXie
 * @LastEditTime: 2020-09-02 12:56:28
 * @Description: 登录验证中间件
 * @FilePath: /weibo/src/middlewares/loginChecks.js
 */

const { ErrorModel } = require('../model/ResModel')
const { loginCheckFailInfo } = require('../model/ErrorInfo')

/**
 * API登录验证
 * @param {object} ctx ctx
 * @param {} next next
 */
async function loginCheck(ctx, next) {
  if (ctx.session && ctx.session.userInfo) {
    // 已登录
    await next()
    return
  }
  // 未登录
  ctx.body = new ErrorModel(loginCheckFailInfo)

}


/**
 * 页面登录验证
 * @param {object} ctx ctx
 * @param {function} next next 
 */
async function loginRedirect(ctx, next) {
  if (ctx.session && ctx.session.userInfo) {
    // 已登录
    await next()
    return
  }
  // 未登录
  const curUrl = ctx.url
  ctx.redirect('/login?url=' + encodeURIComponent(curUrl))
}

module.exports = {
  loginCheck,
  loginRedirect
}